package com.lcc.forum.demos.web.services.impl;

import com.lcc.forum.demos.web.common.AppResult;
import com.lcc.forum.demos.web.common.ResultCode;
import com.lcc.forum.demos.web.dao.ArticleReplyMapper;
import com.lcc.forum.demos.web.exception.ApplicationException;
import com.lcc.forum.demos.web.model.ArticleReply;
import com.lcc.forum.demos.web.services.IArticleReplyService;
import com.lcc.forum.demos.web.services.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private IArticleService articleService;
    @Override
    public void create(ArticleReply articleReply) {
        //参数校验
        if(articleReply == null || articleReply.getPostUserId() == null
                || articleReply.getArticleId() == null
                || articleReply.getContent() == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        articleReply.setLikeCount(0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //调用DAO,写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        //校验操作结果
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        //操作成功，打印日志
        log.info("回复帖子成功，article id = " + articleReply.getArticleId() + ",user id = " + articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //参数校验
        if (articleId == null || articleId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        //返回result
        return result;
    }
}
